import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
from python_ai.common.xcommon import *
import datetime

image = cv.imread('../../../../../large_data/pic/football.jpg',0)
img = image.copy()
rows, cols = img.shape
print('img', img.shape)

template = cv.imread('../../../../../large_data/CV2/lesson/Day07/football_ball.jpg',0)
h, w = template.shape
print('template', template.shape)

img_norm = img/255
template_norm = template/255

img_norm = img_norm - np.mean(img_norm)  # ATTENTION Template matching must 中心化
template_norm = template_norm - np.mean(template_norm)

dt1 = datetime.datetime.now()
print('1 ...')
res1 = convolution_numpy_acc(img_norm, template_norm)
print('1 done')
dt2 = datetime.datetime.now()
print('numpy acc: ', dt2 - dt1)

res = res1
idx = res.argmax()
cx, cy = np.unravel_index(idx, res.shape)
print('center', cx, cy)
cv.rectangle(image, (cy, cx), (cy + 40, cx + 40), 255, 2)

spr = 1
spc = 2
spn = 0
plt.figure(figsize=[12, 6])


def my_show_img(img, title="no title", trans=None, **kwargs):
    global spn
    spn += 1
    plt.subplot(spr, spc, spn)
    if trans is not None:
        img = trans(img)
    plt.imshow(img, **kwargs)
    plt.axis('off')
    plt.title(title)


my_show_img(image, 'ori', cmap='gray')
my_show_img(res, 'res', cmap='gray')
